﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.IO;
using System.Globalization;

namespace cn.Util
{
    /// <summary>
    /// 读取配置文件
    /// </summary>
    public class WebConfig
    {
        /// <summary>
        /// 当前是不是winform程序
        /// </summary>
        public static bool IsWinform
        {
            get
            {
                return  System.Web.HttpContext.Current == null ? true : false;
            }
        }


        private static string _SaveFliePath = string.Empty;

        /// <summary>
        /// 站点配置文件路径
        /// </summary>
        public static string SaveFliePath
        {
            get
            {
                if (string.IsNullOrEmpty(_SaveFliePath))
                {
                    string temp = System.Configuration.ConfigurationManager.AppSettings["SaveFliePath"];

                    if (temp == null)
                    {
                        throw new Exception("配置文件ConfigPath不存在");
                    }
                  
                   _SaveFliePath = IsWinform ? Path.GetFullPath(temp) : PathHelp(temp);
                }

                return _SaveFliePath;
            }
        } 


        private static string _ConfigFilePath = string.Empty;

        /// <summary>
        /// 站点配置文件路径
        /// </summary>
        public static string ConfigFilePath
        {
            get
            {
                if (string.IsNullOrEmpty(_ConfigFilePath))
                {
                    string temp = System.Configuration.ConfigurationManager.AppSettings["ConfigPath"];

                    if (temp == null)
                    {
                        throw new Exception("配置文件ConfigPath不存在");
                    }
               
                    bool isWinform = System.Web.HttpContext.Current == null ? true : false;

                    _ConfigFilePath =isWinform ? Path.GetFullPath(temp):PathHelp(temp);
                }

                return _ConfigFilePath;
            }
        } 

        /// <summary>
        /// 将path和相对路径合并 组成新的路径
        /// </summary>
        /// <param name="path"></param>
        /// <param name="relativelyPath"></param>
        /// <returns></returns>
        public static string PathHelp(string relativelyPath)
        {
            return System.Web.HttpContext.Current.Server.MapPath(relativelyPath);
        }

        /// <summary>
        /// 获取配置文件并转换相应类型
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T AppSetting<T>(string key)
        {
            string  temp = System.Configuration.ConfigurationManager.AppSettings[key];

            return (T)Convert.ChangeType(temp, typeof(T), CultureInfo.InvariantCulture); ;
        }
    }
}
